<?php
declare(strict_types=1);
/**
 * MineAdmin is committed to providing solutions for quickly building web applications
 * Please view the LICENSE file that was distributed with this source code,
 * For the full copyright and license information.
 * Thank you very much for using MineAdmin.
 *
 * @Author X.Mo<root@imoi.cn>
 * @Link   https://gitee.com/xmo/MineAdmin
 */

namespace Plugin\Attractions\Commerce\Service\Commerce_address;

use Plugin\Attractions\Commerce\Repository\Commerce_address\CommerceAddressRepository;
use App\Service\IService;

/**
 * 快递地址信息服务类
 */
final class CommerceAddressService extends IService
{
    public function __construct(
        protected readonly CommerceAddressRepository $repository
    ) {}

    public function apiCreate(array $data): mixed
    {
        if (isset($data['is_default']) && $data['is_default'] == 2) {
            $this->repository->getQuery()
                ->where('is_default', 2)
                ->where('user_id', $data['user_id'])
                ->update(['is_default' => 1]);
        } else {
            $data['is_default'] = 1;
        }
        return $this->repository->create($data);
    }

    public function apiUpdate(mixed $id, array $data): mixed
    {
        if (isset($data['is_default']) && $data['is_default'] == 2) {
            $this->repository->getQuery()
                ->where('is_default', 2)
                ->where('user_id', $data['user_id'])
                ->update(['is_default' => 1]);
        } else {
            $data['is_default'] = 1;
        }
        return $this->repository->updateById($id, $data);
    }
}